#!/usr/bin/env python 2.7
# -*- coding: utf-8 -*-
# @Time      :2021/6/8
# @Author    :zhangxuchuo
# @Email     :zhangxuchuo@bbdservice.com
# @File      :IC103_IndUnsettledGuarantyConsBalance
# @Software  :PyCharm


'''eof
name:申请人未结清担保交易关注类余额
code:IC103_IndUnsettledGuarantyConsBalance
tableName:
columnName:
groups:个人征信模块
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import json
import re
import sys
import datetime
import pandas as pd

# reload(sys)
# sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--', []]


def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
    '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]


def isFloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x) >= 0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def Formate(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                except:
                    date = None
    return date

# 1.FACTOR = sum(相关还款责任信息段(PD03A)·五级分类(PD03AD05)为“2(关注)”的余额（PD03AJ02）)
# 2.五级分类相关缺失值判断（注：非由于五级分类影响产生的缺失值逻辑根据所有指标通用缺失值逻辑确认）：若策略受五级分类为空影响返回缺失值，则判断业务种类是否为81贷记卡、71准贷记卡、82大额专项分期卡，若是则通过，若不是则仍然判断为缺失值；
# list=[]
# IF 五级分类(PD03AD05) 为空 and 业务种类[PD03AD02] in [71,81,82]
# list.append(0)
# elseif 五级分类(PD03AD05) 为空  and 业务种类[PD03AD02] notin [71,81,82]
# list.append(None)

def IC103_IndUnsettledGuarantyConsBalance():
    data = IC_DSJ_2D.get('data')
    #PCR 相关还款责任信息 [1..1]
    PCR = getTable(data, 'PCR', 1, 0)
    account = []
    if PCR == [{}]:
        return '缺失值'
    elif PCR == 0:
        return 0
    else:
        #PD03 相关还款责任信息单元 [0..*]
        PD03 = getTable(PCR[0], 'PD03', 0, 0)
        if PD03 == [{}]:
            return '缺失值'
        elif PD03 == 0:
            return 0
        else:
            for i in PD03:
                #PD03A 相关还款责任信息段 [1..1]
                PD03A = getTable(i, 'PD03A', 1, 1)
                if PD03A == [{}] or PD03A == 0:
                    pass
                else:
                    # PD03AD05 五级分类
                    PD03AD05 = PD03A[0].get('PD03AD05')
                    # PD03AJ02 余额
                    PD03AJ02 = PD03A[0].get('PD03AJ02')
                    # PD03AD02 业务种类
                    PD03AD02 = PD03A[0].get('PD03AD02')
                    if PD03AD05 not in null_type_list:
                        if isFloat(PD03AJ02):
                            if PD03AD05 == '2':
                                account.append(float(PD03AJ02))
                        else:
                            account.append('缺失值')
                    else:
                        if PD03AD02 not in null_type_list and PD03AD02 in ['71', '81', '82']:
                            account.append(0)
                        else:
                            account.append('缺失值')

    if len(list(set(account))) == 1 and list(set(account))[0] == '缺失值':
        return '缺失值'
    else:
        res = [i for i in account if i != '缺失值']
        return sum(res)

result = IC103_IndUnsettledGuarantyConsBalance()
if __name__ == '__main__':
    with open(r'C:\Users\john\Desktop\samples\case(10).json',encoding='utf8') as ff:
        dd = json.loads(ff.read())
    IC_DSJ_2D = dd['IC_DSJ_2D']
    result = IC103_IndUnsettledGuarantyConsBalance()
    print(result)